//
//  ViewController.swift
//  WeatherTest
//
//  Created by WuZhijian on 14/11/24.
//  Copyright (c) 2014年 com.tianqi.livecn. All rights reserved.
//

import UIKit
import CoreLocation;

class ViewController: UIViewController,CLLocationManagerDelegate {
    
    let locationManager:CLLocationManager = CLLocationManager()

    @IBOutlet weak var location: UILabel!
    
    @IBOutlet weak var icon: UIImageView!
    
    @IBOutlet weak var temperature: UILabel!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        
        locationManager.delegate = self;
        locationManager.desiredAccuracy = kCLLocationAccuracyBest;
        if(ios8())
        {
            locationManager.requestAlwaysAuthorization();
        }
        
        locationManager.startUpdatingLocation();
    }
    
    func ios8() -> Bool
    {
        return UIDevice.currentDevice().systemVersion == "8.1.1";
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!)
    {
        var location:CLLocation = locations[locations.count-1] as CLLocation
        
        if(location.horizontalAccuracy > 0)
        {
            //println(location.coordinate.latitude)
            //println(location.coordinate.longitude)
            self.updateWeatherInfo(location.coordinate.latitude,lng: location.coordinate.longitude);
            locationManager.stopUpdatingLocation();
        }
    }
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!)
    {
        println(error);
    }
    
    func updateWeatherInfo(lat:CLLocationDegrees,lng:CLLocationDegrees)
    {
        let manager = AFHTTPRequestOperationManager();
        let url = "http://api.openweathermap.org/data/2.5/weather"
        
        let params = ["lat":lat,"lon":lng,"cnt":0]
        
        manager.GET(
            url,
            parameters: params,
            success: {
                (operation:AFHTTPRequestOperation!, responseObject:AnyObject!) -> Void in
                  //println("JSON:"+responseObject.description)
                  self.updateUISuccess(responseObject as NSDictionary);
            },
            failure:{
                (operation:AFHTTPRequestOperation!, error:NSError!) -> Void in
                    println(error)
                //self.loadding.text = " Internet appears down !"
        }
    )}
    
    func updateUISuccess(result:NSDictionary!)
    {
        if let tempResult = result["main"]?["temp"]? as? Double
        {
            var temp : Double
            if(result["sys"]?["country"]? as String == "US")
            {
                temp = round(((tempResult - 273.15)*1.8)+32)
            }else
            {
                temp = round(tempResult - 273.15)
            }
            
            self.temperature.text = "\(temp)℃"
            self.temperature.font = UIFont.boldSystemFontOfSize(60)
            
            var name = result["name"]? as String
            self.location.text = "\(name)"
            self.temperature.font = UIFont.boldSystemFontOfSize(60)
            
        }
        else
        {
            self.temperature.text = "0℃"
        }
    }
}
